<template>
  <div>
    <div class="content">{{$t('km.content')}}</div>
    <div class="file-upload">
      <el-upload
        :action="uploadUrl"
        :data=uploadHeaders
        name="upload"
        accept=".doc,.docx,.xls,.xlsx"
        :on-preview="handlePreview"
        :with-credentials="true"
        :on-success="handleSuccess"
        :before-upload="beforeUploadfile"
        :on-remove="handleRemove"
        :default-file-list="fileList">
        <em class="add-file">{{$t('km.addFile')}}</em>
        {{$t('km.fileDescription')}}
      </el-upload>
    </div>
    <div class="quill">
      <!--<div id="km_editor_menu"></div>-->
      <div id="km_editor_content"></div>
      <!--<quill-editor ref="editor" :editdata="editdata" @submitContent="submitContent"></quill-editor>-->
    </div>
    <div class="attachment-upload" v-if="KmType === 'inner'">
      <el-form label-position="right" :rules="rules" ref="form" :model="form">
        <el-form-item :label="$t('km.uploadAttachment')" prop="">
          <el-button type="text" class="iconfont icon-fujian" id="uploadKmFile" :disabled="progressUi.show"></el-button><span class="upload-size">{{$t('km.attachmentDescription')}}</span>
          <div>
            <div v-for="(file, index) in form.kmFile" v-if="form.kmFile.length" class="fujian-div">
              <a :href="km.getKmUrl(file,{ useAttname: true, isOriginFile: true })" download target="_blank" class="text-color">{{file.name}}</a>
              <span class="delete" @click="deleteFile(file.id, index)">
                  <i class="el-icon-close"></i>
                </span>
              <!--<el-button @click="deleteFile(file.id, index)" :disabled="disabled">{{$t('public.delete')}}</el-button>-->
            </div>
            <div class="process-ui" v-if="progressUi.show">
              <span>{{progressUi.fileName}}</span>
              <el-progress :text-inside="true" :stroke-width="18" :percentage="progressUi.percent" :status="progressUi.type"></el-progress>
            </div>
          </div>
          <input type="hidden" v-model.trim="form.kmFile"/>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll :title="$t('km.preview')" :visible.sync="editorDialog.isShow" width="800px">
      <div v-html="editorDialog.content" class="editor-preview">
      </div>
    </el-dialog>
  </div>
</template>
<script>
//  import quillEditor from '@/components/business-modules/km/km-detail/QuillEditor.vue'
  import {uploadTo7moorKmDomain, uploadTo7moorKmImgDomain, PasteImguploadTo7moorKmDomain, qiniu7moorKmDomain} from '@/utils/qiniuUtils'
  import {getCurrentDate, filterXSS} from '@/utils/m7Utils'
  import Editor from 'wangeditor'
  import { km } from '@/utils/cosUrl'
  import * as uuid from 'uuid'
  export default {
    name: 'QuillPublic',
    props: {
      editdata: Array,
      attachs: {type: Array, default: function () { return [] }},
      itemId: String,
      KmType: String
    },
    data () {
      let validate1 = (rule, value, callback) => {
        if (value.length === 0 || value === undefined) {
          callback(new Error(this.$t('validate.required')))
        } else {
          callback()
        }
      }
      return {
        km,
        uploadUrl: '/kmUpload',
        uploadHeaders: {
          type: 'undefined',
          module: '',
          sessionId: this.$store.state.session.sessionId
        },
        subContent: [],
        wEditor: {},
        form: {
          kmFile: this.attachs || []
        },
        rules: {
          kmFile: [
            {validator: validate1, required: true, trigger: 'change'}
          ]
        },
        progressUi: {
          show: false,
          percent: 0,
          type: 'success',
          fileName: '',
          disabled: false
        },
        domain: this.$store.state.fileDomain.cos7moorKmDomain,
        qiniu7moorKmDomain,
        fileList: {
        },
        m7uploaders: [],
        editorDialog: {
          isShow: false,
          content: ''
        }
      }
    },
    watch: {
    },
    computed: {
      attachmentMaxSize () {
        return this.$store.state.attachmentMaxSize
      }
    },
    methods: {
      handlePreview () {
      },
      handleRemove () {
      },
      // 预览
      preview () {
        this.editorDialog.isShow = true
        this.editorDialog.content = this.wEditor.txt.html()
        // table加border
        if (new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(this.editorDialog.content)) {
          this.editorDialog.content = this.editorDialog.content.replace(/<table border="0" width="100%" cellpadding="0" cellspacing="0">/g, '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">')
        }
      },
      pasteImg (evnet) {
        let ele = evnet.clipboardData.items || []
        let account = this.$store.state.session.user.account
        let that = this
        for (let i = 0; i < ele.length; ++i) {
          if (ele.length === 1 && ele[i].kind === 'file' && ele[i].type.indexOf('image/') !== -1) {
            let blob = ele[i].getAsFile()
            let filename = 'clipboard' + new Date().getTime() + '.png'
            let key = function (up, file) {
              let date = getCurrentDate()
              let today = new Date()
              let time = today.getTime()
              //          let fileName = file.name
              //          let fileSuffix = ''
              //          if (fileName) {
              //            fileSuffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
              //          }
              let key = account + '/km/' + date + '/' + time + '/' + uuid.v1() + file.name
              return key
            }
            let key1 = key()
            let uploadProgress = function (up, file) {
            }
            let fileUploaded = function (up) {
              let domain = that.$store.state.isUseQiniu ? qiniu7moorKmDomain : that.$store.state.fileDomain.cos7moorImDomain
              let sourceLink = domain + (that.$store.state.isUseQiniu ? up.key : file.fileKey) // 获取上传成功后的文件的Url
              // that.wEditor.txt.append('<img src="' + sourceLink + '" alt="">')
              // 改为图片在光标出插入
              that.wEditor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
//              that.sendChatMsg.content = sourceLink
//              that.handleSubmit({}, 'image')
//              that.uploaded.uploadImg = false
              that.subContent.content = that.wEditor.txt.html()
              that.$emit('submitContent', that.subContent)
            }
            PasteImguploadTo7moorKmDomain(this.$store.state.session.user._id, blob, filename, uploadProgress, fileUploaded, key1)
          }
        }
      },
      beforeUploadfile (file) {
        let arr = file.name.split('.')
        let arrType = ['doc', 'docx', 'xls', 'xlsx']
        if (arrType.indexOf(arr[arr.length - 1]) !== -1) {
          if (file.size > 2 * 1024 * 1024) {
            this.$message.error(this.$t('km.attachSizeOverLimit2'))
            return false
          } else {
            return true
          }
        } else {
          this.$message.error(this.$t('km.uploadFileWrong'))
          return false
        }
      },
      handleSuccess (response, file, fileList) {
        let split = response.filePath.split('/')
        let length = split.length - 1 // 线上环境不能写死2，而是最后一级
        let obj = {
          fileName: split[length],
          trueName: response.fileName
        }
        let loading = this.$loading({fullscreen: true, text: this.$t('km.loading')})
        this.$store.dispatch('uploadDoc', obj).then((val) => {
          loading.close()
          let uploadDoc = this.$store.state.km.uploadDoc
          if (uploadDoc) {
            this.editdata.content = uploadDoc.html
            this.editdata.fileId = uploadDoc.fileId
            this.subContent.fileId = uploadDoc.fileId
            this.subContent.content = uploadDoc.html
            this.wEditor.txt.html(filterXSS(uploadDoc.html))
            this.$emit('submitContent', this.subContent)
          }
        })
      },
      submitContent (submitContent) {
        this.subContent.content = submitContent
        this.$emit('submitContent', this.subContent)
      },
      initUploadKmFile (ev) {
        let account = this.$store.state.session.user.account
        let that = this
        let filters = {}
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          that.progressUi.show = true
          that.progressUi.percent = 0
          that.progressUi.fileName = file.name
          console.log('beforeUpload')
        }
        let uploadProgress = function (up, file) {
          that.progressUi.percent = file.percent
          console.log('uploadProgress')
        }
        let uploadComplete = function () {
          that.progressUi.show = false
          console.log('uploadComplete')
        }
        let fileUploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (that.$store.state.isUseQiniu ? res.key : file.fileKey)
          let obj = {
            name: file.name,
            id: sourceLink
          }
          if (that.form.kmFile) {
            that.form.kmFile.push(obj)
          } else {
            that.form.kmFile = []
            that.form.kmFile.push(obj)
          }
          that.$emit('kmFile', that.form.kmFile)
        }
        let error = function (up, err, errTip) {
          if (err.code === -600) {
            that.$message.error(that.$t('km.attachmentMaxDescription'))
          }
          console.log('uploadError ' + errTip)
        }
        this.m7uploaders.push(
          uploadTo7moorKmDomain(this.$store.state.session.user._id, 'uploadKmFile', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, km.getUploadKey, this.attachmentMaxSize)
        )
      },
      initUploadImageFile () {
        let account = this.$store.state.session.user.account
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          console.log('uploadProgress1')
        }
        let uploadComplete = function (up, file) {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          if (!self.wEditor.txt.html()) {
            self.wEditor.txt.html('')
          }
          // self.wEditor.txt.append('<img src="' + sourceLink + '" alt="">')
          // 改为图片在光标出插入
          self.wEditor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
          self.subContent.content = self.wEditor.txt.html()
          self.$emit('submitContent', self.subContent)
        }
        let error = function (up, err, errTip) {
          if (errTip) {
            self.$message.error(errTip)
          }
          console.log('uploadError ' + errTip)
        }
        let key = function (up, file) {
          let date = getCurrentDate()
          let today = new Date()
          let time = today.getTime()
//          let fileName = file.name
//          let fileSuffix = ''
//          if (fileName) {
//            fileSuffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
//          }
          let key = account + '/km/' + date + '/' + time + '/' + uuid.v1() + file.name
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp'}
          ]
        }
        this.m7uploaders.push(
          uploadTo7moorKmImgDomain(this.$store.state.session.user._id, 'kmUploadImageFile', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
        )
      },
      deleteFile (fileId, index) {
        let _id = fileId.split('.')[2]
        let key = ''
        let split = _id.split('/')
        for (let i = 1; i <= split.length - 1; i++) {
          if (i < split.length - 1) {
            key += split[i] + '/'
          } else {
            key += split[i]
          }
        }
        let kmFile = this.form.kmFile || []
        let attach = {}
        for (let i = 0; i < kmFile.length; i++) {
          let id1 = kmFile[i].id.split('.')[2]
          let key1 = ''
          let split1 = id1.split('/')
          for (let i = 1; i <= split1.length - 1; i++) {
            if (i < split1.length - 1) {
              key1 += split1[i] + '/'
            } else {
              key1 += split1[i]
            }
          }
          if (key1 !== key) {
            attach[key1] = kmFile[i].name
          }
        }
        let data = {
          _id: this.itemId,
          attachs: attach,
          delId: key
        }
        this.$emit('kmFile', this.form.kmFile)
        this.$store.dispatch('delAttach', data).then((res) => {
          this.form.kmFile.splice(index, 1)
        })
      },
      initAttachs () {
        for (let i = 0; i < this.attachs.length; i++) {
          let attach = this.attachs[i]
          let obj = {
            name: attach.split(':')[1],
            id: attach.split(':')[0]
          }
          this.form.kmFile.push(obj)
        }
      },
      initEditor () {
        this.wEditor = new Editor('#km_editor_content')
        this.wEditor.config.menus = [
          'head',  // 标题
          'bold',  // 粗体
          'fontSize',  // 字号
          'fontName',  // 字体
          'italic',  // 斜体
          'underline',  // 下划线
          'strikeThrough',  // 删除线
          'foreColor',  // 文字颜色
          'backColor',  // 背景颜色
          'link',  // 插入链接
          'list',  // 列表
          'justify',  // 对齐方式
//          'quote',  // 引用
//          'emoticon',  // 表情
          'table',  // 表格
          // 'code',  // 插入代码
          'undo',  // 撤销
          'redo'  // 重复
        ]
        this.wEditor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
        this.wEditor.config.onchange = (html) => {
//         html 即变化之后的内容
//          this.mailSignatureClone.content = this.wEditor.txt.html()
          this.subContent.content = this.wEditor.txt.html()
          if (new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(this.subContent.content)) {
            this.subContent.content = this.subContent.content.replace(/<table border="0" width="100%" cellpadding="0" cellspacing="0">/g, '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">')
          }
          this.$emit('submitContent', this.subContent)
          this.$emit('kmFile', this.form.kmFile)
        }
        this.wEditor.config.zIndex = 100
        let lang = window.langJson || {}
        let editLang = lang.wangeditor
        this.wEditor.config.lang = editLang
        this.wEditor.create()
        let div = document.createElement('div')
        div.className = 'w-e-menu'
        div.style.cssText = 'z-index:101;'
        let span = document.createElement('i')
        span.className = 'w-e-icon-image'
        span.id = 'kmUploadImageFile'
        div.appendChild(span)
        // document.getElementsByClassName('w-e-toolbar')[0].appendChild(div)
        document.querySelector('#km_editor_content .w-e-toolbar').appendChild(div)
        this.initUploadImageFile()
        let self = this
        // document.getElementsByClassName('w-e-text')[0].addEventListener('paste', self.pasteImg)
        document.querySelector('#km_editor_content .w-e-text').addEventListener('paste', self.pasteImg)
        this.$emit('kmFile', this.form.kmFile)
      }
    },
    create () {
      this.initAttachs()
    },
    mounted () {
      this.initUploadKmFile()
      let value = this.form.kmFile
//      let btn = document.getElementsByClassName('ql-kmUpLoadFile')[0]
//      let name = btn.className
//      btn.className = name + ' iconfont icon-tupianicon'
//      btn.id = 'kmUploadImageFile'
      this.initEditor()
      setTimeout(() => {
        this.wEditor.txt.html(filterXSS(this.editdata.content))
      }, 1000)
      this.$emit('tellme', {[this.id]: value})
    },
    beforeDestroy () {
      this.m7uploaders.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
    },
    components: {
//      quillEditor,
      Editor
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl";
  .text-color
    color $cf-gray0
    vertical-align middle
  .fujian-div
    display inline-block
    background-color #d1f6f8
    line-height normal
    padding 5px
    margin-right 10px
    height 20px
    font-size 14px
    vertical-align top
  .delete
    color $c-main
    padding-left 10px
    vertical-align middle
  .content
    color $cf-gray1
    padding-bottom 5px
  .file-upload
    .el-upload
      color $cf-gray3
      width auto
      .add-file
        font-style normal
        color $c-main
  .quill
    margin 10px 0 10px
  .attachment-upload
    margin-bottom 30px
    .icon-dakailianjie
      color $c-main
      padding-left 15px
  .upload-size
    color $cf-gray3
    font-size 12px
  .quill
    color $cf-gray0
  .editor-preview
    min-height 200px
    max-height 60vh
    overflow-y auto
</style>
